<template>
  <div class="main-box">
    <div class="card content-box w-full">
      <TableContainer
        :is-page="true"
        :page-info="{ current: page, pageSize: pageSize, total: total }"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
        <template #searchCard>
          <SearchFrom :search-event="handleSearchEvent" />
        </template>
        <template #btnLeft>
          <el-button v-auth="['role:add:btn']" type="primary" @click="handleAdd">
            <el-icon>
              <Plus />
            </el-icon>
            新增
          </el-button>
        </template>
        <el-table
          v-bind="$attrs"
          :data="[...tableData]"
          row-key="id"
          :height="gridOptions.height"
          :show-overflow-tooltip="gridOptions.showOverflow"
        >
          <template #empty>
            <span>暂无数据</span>
          </template>
          <el-table-column
            v-for="item in gridOptions.columns"
            :type="item.type ? item.type : 'default'"
            v-bind="{ ...item, ...$attrs }"
            :key="item.prop"
          >
            <template #default="{ row }">
              <div class="w-full flex items-center" v-if="item.slots === 'controls'">
                <el-button v-auth="['role:edit:btn']" link type="primary" @click="handleEdit(row)">
                  <el-icon>
                    <EditPen />
                  </el-icon>
                  编辑
                </el-button>
                <el-button link v-auth="['role:permission:btn']" type="primary" @click="handleOpenDrawer(row)">
                  <el-icon>
                    <Connection />
                  </el-icon>
                  分配
                </el-button>
                <el-button link v-auth="['role:delete:btn']" type="danger" @click="handleDelete(row)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </TableContainer>
    </div>
    <RoleAdd ref="roleAddRef" @close="handleClose"></RoleAdd>
    <AssignPermissions ref="assignPermissionsRef"></AssignPermissions>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage } from "element-plus";
import { useComponentRef } from "@/hooks/useComponentRef";
import SearchFrom from "./components/SearchFrom.vue";
import { getRoleDetail, getRoleList, removeRole } from "@/api/modules/role";
import { Role } from "@/api/interface";
import { useTableConfig } from "@/hooks/useTable";
import TableContainer from "@/components/TableContainer/index.vue";
import { usePagination } from "alova/client";

const RoleAdd = defineAsyncComponent(() => import("./components/Add.vue"));
const AssignPermissions = defineAsyncComponent(() => import("./components/AssignPermissions.vue"));
const roleAddRef = useComponentRef(RoleAdd);
const assignPermissionsRef = useComponentRef(AssignPermissions);

const queryForm = ref<Role.IRoleParams>({});

const { gridOptions } = useTableConfig({
  columns: [
    { prop: "roleName", label: "角色名称" },
    { prop: "roleCode", label: "角色标识" },
    { prop: "description", label: "描述" },
    { prop: "sortOrder", label: "排序" }
  ],
  controlsWidth: 240
});

const {
  data: tableData,
  page,
  pageSize,
  total,
  send
} = usePagination(
  (page, pageSize) =>
    getRoleList({
      current: page,
      size: pageSize,
      ...queryForm.value
    }),
  {
    force: true,
    total: response => response.data?.pager?.total || 0,
    data: response => response.data?.records ?? []
  }
);

const handleSearchEvent = (form: Role.IRoleParams) => {
  queryForm.value = form;
  send();
};

const handleAdd = () => {
  roleAddRef.value?.openDialog();
};

const handleEdit = async (row: Role.IRole) => {
  try {
    if (!row.id) return;
    const { data } = await getRoleDetail(row.id);
    roleAddRef.value?.openDialog("edit", data);
  } catch (e) {
    console.error(e);
  }
};

const handleDelete = async (row: Role.IRole) => {
  try {
    if (!row.id) return;
    await removeRole(row.id);
    ElMessage.success("删除成功");
    await send();
  } catch (e) {
    console.error(e);
  }
};
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  page.value = 1;
};
const handleCurrentChange = (current: number) => {
  page.value = current;
};
const handleClose = () => {
  send();
};

const handleOpenDrawer = (row: Role.IRole) => {
  assignPermissionsRef.value?.openDialog(row);
};
</script>
